package com.rgs.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.rgs.ssm.dao.IUserDao;
import com.rgs.ssm.domain.Role;
import com.rgs.ssm.domain.UserInfo;
import com.rgs.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @create 2021-02-18 18:57
 *
 * 用户模块，业务层
 **/
@Service
@Transactional
public class UserService implements IUserService {

    @Autowired
    private IUserDao userDao;

    /**
     * SpringSecurity完成验证密码角色。
     * @param username
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String username){
        //调用dao层，根据username来返回对应的用户对象
        UserInfo userInfo = userDao.findByUsername(username);
        //将我们自己的用户对象封装成UserDetails对象
        User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(), getAuthorList(userInfo.getRoles()));
        return user;
    }

    /**
     * 获取用户对应的角色
     * @return
     */
    public List<SimpleGrantedAuthority> getAuthorList(List<Role> roles) {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        //循环添加该用户的所有角色
        for (Role role : roles) {
            //拼接角色关键字
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return list;
    }


    @Override
    public void saveUser(UserInfo userInfo) {
        //对密码进行加密
        /*String encryptedPassword = BCryptPasswordEncoderUtils.encodePassword(userInfo.getPassword());
        userInfo.setPassword(encryptedPassword);*/
        userDao.saveUser(userInfo);
    }

    @Override
    public void delete(Integer id) {
        userDao.delete(id);
    }

    @Override
    public void update(UserInfo userInfo) {
        userDao.update(userInfo);
    }

    @Override
    public UserInfo findById(Integer userId) {
        return userDao.findById(userId);
    }

    /**
     * 使用PageHelper插件进行分页
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<UserInfo> findAll(int page,int size) {
        PageHelper.startPage(page,size);
        return userDao.findAll();
    }

    /**
     * 根据用户id，返回用户没有的角色
     * @param userId
     * @return
     */
    @Override
    public List<Role> findByIdOtherRole(Integer userId){
        return userDao.findByIdOtherRole(userId);
    }

    /**
     * 给用户添加角色
     * @param userId
     * @param roleIds
     */
    @Override
    public void addRoleToUser(Integer userId, Integer[] roleIds) {
        for (Integer roleId : roleIds) {
            userDao.addRoleToUser(userId,roleId);
        }
    }
}
